import { LOCAL_DATA_DIR } from './constant'

// 生成项目ID
function generateProjectId() {
  return (+new Date()).toString(36)
}

// 保存项目数据
export function saveLocalProject(projectData) {
  // 确保本地数据目录存在
  if (!localStorage.getItem(LOCAL_DATA_DIR)) {
    localStorage.setItem(LOCAL_DATA_DIR, JSON.stringify({}));
  }
  
  const projectId = projectData.flag || generateProjectId();
  projectData.flag = projectId;
  projectData.updateTime = new Date().toISOString();
  
  try {
    const localData = JSON.parse(localStorage.getItem(LOCAL_DATA_DIR) || '{}');
    localData[projectId] = projectData;
    localStorage.setItem(LOCAL_DATA_DIR, JSON.stringify(localData));
    return Promise.resolve(projectId);
  } catch (error) {
    return Promise.reject(error);
  }
}

// 获取所有项目数据
export function getAllLocalProjects() {
  try {
    const localData = JSON.parse(localStorage.getItem(LOCAL_DATA_DIR) || '{}');
    return Promise.resolve(Object.values(localData));
  } catch (error) {
    return Promise.reject(error);
  }
}

// 获取项目列表（带分页）
export function getLocalProjectList(pageNo = 1, pageSize = 6) {
  return getAllLocalProjects().then(projects => {
    const sortedProjects = projects.sort((a, b) => new Date(b.updateTime) - new Date(a.updateTime));
    const start = (pageNo - 1) * pageSize;
    const end = start + pageSize;
    return {
      list: sortedProjects.slice(start, end),
      count: sortedProjects.length
    };
  });
}

// 根据ID获取单个项目
export function getLocalProjectById(projectId) {
  return getAllLocalProjects().then(projects => {
    return projects.find(p => p.flag === projectId) || null;
  });
}

// 删除项目
export function deleteLocalProject(projectId) {
  try {
    const localData = JSON.parse(localStorage.getItem(LOCAL_DATA_DIR) || '{}');
    delete localData[projectId];
    localStorage.setItem(LOCAL_DATA_DIR, JSON.stringify(localData));
    return Promise.resolve();
  } catch (error) {
    return Promise.reject(error);
  }
}